package com.smartfast4j.api.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smartfast4j.api.common.bean.IpInfo;
import com.smartfast4j.api.service.ApiService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ApiServiceImpl implements ApiService {

    @Value("${api.url.ipSearch}")
    private String ipSearch;

    @Override
    public IpInfo searchIp(String ip) {
        IpInfo ipInfo = new IpInfo();
        if(StringUtils.isEmpty(ip)){
            return ipInfo;
        }
        //调用第三方接口查询IP地址信息
        String retVal =  HttpUtil.get(ipSearch+"?ip="+ip);
        if(StringUtils.isNotEmpty(retVal)){
            JSONObject resJson = JSON.parseObject(retVal);
            ipInfo.setIp(ip);
            if(resJson.getInteger("code")==0){//0：成功，1：失败
                JSONObject data = resJson.getJSONObject("data");
                ipInfo.setProvince(data.getString("region"));
                ipInfo.setCity(data.getString("city"));
                ipInfo.setIsp(data.getString("isp"));
            }else {
                ipInfo.setProvince("未知");
                ipInfo.setCity("未知");
                ipInfo.setIsp("未知");
            }
        }
        return ipInfo;
    }
}
